package per.destiny.seckill.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import per.destiny.seckill.service.OrderService;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SeckillProducer {

    @Autowired
    private OrderService orderService;

    private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(5,
            100,
            1,
            TimeUnit.MINUTES,
            new ArrayBlockingQueue<>(1000), new BasicThreadFactory.Builder().namingPattern("seckill_thread_%s").build(),
            new ThreadPoolExecutor.CallerRunsPolicy());


    /**
     * 发送MQ消息，以及接受MQ消息并处理
     *
     * @param userId
     * @param goodsId
     */
    public void sendSeckillMessage(Long userId, Long goodsId) {
        THREAD_POOL_EXECUTOR.execute(new Runnable() {
            @Override
            public void run() {
                orderService.seckillMessage(userId, goodsId);
            }
        });
    }
}
